package com.whmnx.my.ui.viewmodel;

import android.app.Application;
import android.app.Dialog;
import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.whmnx.base.bean.BeanRecordBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.utils.CommonUtil;
import com.whmnx.base.utils.UItils;
import com.whmnx.base.view.CommonDialog;
import com.whmnx.my.R;
import com.whmnx.my.ui.fragment.MyBalanceFragment;
import com.whmnx.my.ui.fragment.MyTranBalancesFragment;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * author : huang
 * date   : 2020/9/24 0024 18:14
 * version: 1.0
 * @author Administrator
 */
public class BalanceModel extends ToolbarViewModel implements View.OnClickListener {
    public ObservableField<String> balance = new ObservableField<>("");
    private Dialog dialogHead;
    private MyBalanceFragment activity;
    private  MyBalanceFragment mFragment;

    public ObservableField<String> awardRef = new ObservableField<>("");
    public ObservableField<String> awardRefVendor = new ObservableField<>("");
    public ObservableField<String> totalStayAward = new ObservableField<>("");
    public ObservableField<String> reward = new ObservableField<>("");
    private double balance1;

    private PopupWindow mValidatePayPasswordPopWindow;

    private EditText et_password;

    private String alreadyInputPassword;
    private boolean isFirstInputPassword = true;
    private boolean isCanClear = true;
    private int zhuanType;
    private String input2;
    private String s3;


    public BalanceModel(@NonNull Application application) {
        super(application);
    }

    public void initToolbar(MyBalanceFragment myBalanceFragment) {
        this.mFragment = myBalanceFragment;
        setTitleText("播豆余额");
        setRightText("交易余额");
        setRightTextVisible(View.VISIBLE);
        this.activity = myBalanceFragment;
        initView();
    }

    private void initView() {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        params.put("pageIndex",1);
        params.put("pageSize",100);
        HttpClient.post(mFragment.getActivity(), Constants.GETASSETBALANCE, params,new CallBack<BeanRecordBean>() {
            @Override
            public void onSuccess(BeanRecordBean beanRecordBean) {
                balance1 = beanRecordBean.getBalance();
                balance.set(beanRecordBean.getBalance() + "");
                awardRef.set(beanRecordBean.getAwardRef());
                awardRefVendor.set(beanRecordBean.getAwardRefVendor());
                totalStayAward.set(beanRecordBean.getTotalStayAward());
                reward.set(beanRecordBean.getReward());
                observableList.clear();
                for (BeanRecordBean.BeanRecordListBean beanRecordListBean : beanRecordBean.getBeanRecordList()) {
                    observableList.add(new WithdrawItemViewModel2(BalanceModel.this,beanRecordListBean));
                }
            }
        });
    }


    //给RecyclerView添加ObservableList
    public ObservableList<WithdrawItemViewModel2> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<WithdrawItemViewModel2> itemBinding = ItemBinding.of(com.whmnx.my.BR.viewModel, R.layout.item_balance);


    @Override
    protected void rightTextOnClick() {
        startContainerActivity(MyTranBalancesFragment.class.getCanonicalName());
    }


    //互转
    public BindingCommand huOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            String s2 = "好友互转";
            new CommonDialog(mFragment.getActivity(), R.style.dialog, s2,3, (dialog, confirm, input, s) -> {
                if (confirm) {
                    String sNum  =  s.toString();
                    if (Double.valueOf(sNum) > balance1){
                        ToastUtil.toastShortMessage("当前余额不足");
                        return;
                    }
                    zhuanType = 0;
                    input2 = input;
                    s3 = s;
                    showPossWord(dialog);
                }
                dialog.dismiss();
            }).show();
        }
    });

    private void showPossWord(Dialog dialog) {
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(mFragment.getActivity()).inflate(R.layout.popwindow_validate_pay_password, null);
        et_password = contentView.findViewById(R.id.et_password);
        final TextView tv_pwd_one = contentView.findViewById(R.id.tv_pwd_one);
        final TextView tv_pwd_two = contentView.findViewById(R.id.tv_pwd_two);
        final TextView tv_pwd_three = contentView.findViewById(R.id.tv_pwd_three);
        final TextView tv_pwd_four = contentView.findViewById(R.id.tv_pwd_four);
        final TextView tv_pwd_five = contentView.findViewById(R.id.tv_pwd_five);
        final TextView tv_pwd_six = contentView.findViewById(R.id.tv_pwd_six);
        final ImageView iv_close = contentView.findViewById(R.id.iv_close);
        final TextView tv_forget_password = contentView.findViewById(R.id.tv_forget_password);
        final TextView tv_money = contentView.findViewById(R.id.tv_money);

        tv_pwd_one.setOnClickListener(this);
        tv_pwd_two.setOnClickListener(this);
        tv_pwd_three.setOnClickListener(this);
        tv_pwd_four.setOnClickListener(this);
        tv_pwd_five.setOnClickListener(this);
        tv_pwd_six.setOnClickListener(this);
        iv_close.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                switch (s.length()) {
                    case 0:
                        if (isCanClear) {
                            tv_pwd_one.setText("");
                        }
                        break;
                    case 1:
                        tv_pwd_one.setText(s.toString().substring(0, 1));
                        tv_pwd_two.setText("");
                        break;
                    case 2:
                        tv_pwd_two.setText(s.toString().substring(1, 2));
                        tv_pwd_three.setText("");
                        break;
                    case 3:
                        tv_pwd_three.setText(s.toString().substring(2, 3));
                        tv_pwd_four.setText("");
                        break;
                    case 4:
                        tv_pwd_four.setText(s.toString().substring(3, 4));
                        tv_pwd_five.setText("");
                        break;
                    case 5:
                        tv_pwd_five.setText(s.toString().substring(4, 5));
                        tv_pwd_six.setText("");
                        break;
                    case 6:
                        if (!isFirstInputPassword) {
                            if (s.toString().equals(alreadyInputPassword)) {
                                //密码通过
                                setPayPwd(alreadyInputPassword,dialog);
                            } else {
                                //  ToastUtil.toastShortMessage("交易密码输入错误");
                            }
                        }
                        tv_pwd_six.setText(s.toString().substring(5, 6));
                        if (isFirstInputPassword) {
                            alreadyInputPassword = s.toString();
                            if (s.toString().equals(alreadyInputPassword))
                                setPayPwd(alreadyInputPassword,dialog);
                        }

                        //  Utils.showToastSafe("支付密码输入错误");
                        tv_pwd_one.setText("");
                        tv_pwd_two.setText("");
                        tv_pwd_three.setText("");
                        tv_pwd_four.setText("");
                        tv_pwd_five.setText("");
                        tv_pwd_six.setText("");
                        isCanClear = false;
                        et_password.setText("");
                        isCanClear = true;
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        mValidatePayPasswordPopWindow = new PopupWindow(contentView,
                (int) (UItils.getDeviceDensity(mFragment.getActivity()).widthPixels / 1.1), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mValidatePayPasswordPopWindow.setContentView(contentView);
        // mValidatePayPasswordPopWindow.setFocusable(true);
        //点击外部消失
        mValidatePayPasswordPopWindow.setOutsideTouchable(true);
        mValidatePayPasswordPopWindow.setBackgroundDrawable(new BitmapDrawable());

        //设置获得焦点，否则无法点击
        //   mValidatePayPasswordPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        //   mValidatePayPasswordPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        View rootView = LayoutInflater.from(mFragment.getActivity()).inflate(R.layout.fragment_about, null);
        mValidatePayPasswordPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        //    openKeybord();
        mValidatePayPasswordPopWindow.setOnDismissListener(() -> setBackgroundAlpha(1));
    }

    private void setPayPwd(String alreadyInputPassword,Dialog dialog) {
        String pasWord = UItils.md5Digest(alreadyInputPassword);
        if (pasWord.equals(SPUtils.getInstance().getString(Constants.PAYWORD))){
            if (zhuanType == 0) {
                Map<String, Object> params = new HashMap<>();
                params.put("uId", SPUtils.getInstance().getString(Constants.USERID));
                params.put("num", s3);
                params.put("friend", input2);
                HttpClient.post(mFragment.getActivity(), Constants.BEANHUZHUAN, params, new CallBack<BeanRecordBean>() {
                    @Override
                    public void onSuccess(BeanRecordBean beanRecordBean) {
                        mValidatePayPasswordPopWindow.dismiss();
                        initView();
                        dialog.dismiss();
                    }
                });
            }else {
                Map<String, Object> params = new HashMap<>();
                params.put("uId", SPUtils.getInstance().getString(Constants.USERID));
                params.put("bean", input2);
                params.put("type", "0");
                HttpClient.get(mFragment.getActivity(), Constants.BEANSTRANSFER, params,new CallBack<BeanRecordBean>() {
                    @Override
                    public void onSuccess(BeanRecordBean beanRecordBean) {
                        mValidatePayPasswordPopWindow.dismiss();
                        initView();
                        dialog.dismiss();
                    }
                });
            }
        }else {
            ToastUtil.toastShortMessage("交易密码输入错误");
        }
    }


    //化转
    public BindingCommand huazhuanOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showPop();
        }
    });


    private void showPop() {
        dialogHead = new Dialog(activity.getActivity(), R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(activity.getActivity()).inflate(R.layout.dialog_pop_huazhuang, null);
        Button btZhuang = view.findViewById(R.id.bt_zhuanghua);
        //划转至交易金额
        btZhuang.setOnClickListener(v -> {
            String s2 = "划转至交易余额";
            new CommonDialog(mFragment.getActivity(), R.style.dialog, s2,1, (dialog, confirm, input, s) -> {
                if (confirm) {
                    String sNum  =  input.toString();
                    if (Double.valueOf(sNum) > balance1){
                        ToastUtil.toastShortMessage("当前余额不足");
                        return;
                    }
                    dialogHead.dismiss();
                    zhuanType = 1;
                    input2 = input;
                    s3 = s;
                    showPossWord(dialog);


                }
                dialog.dismiss();
            }).show();
        });

        view.findViewById(R.id.dialog_photo_album).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        view.findViewById(R.id.dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogHead.dismiss();
            }
        });
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //将属性设置给窗体
        window.setAttributes(lp);
    }

    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = mFragment.getActivity().getWindow().getAttributes();
        lp.alpha = v;
        mFragment.getActivity().getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_pwd_one || id == R.id.tv_pwd_two || id == R.id.tv_pwd_three || id == R.id.tv_pwd_four || id == R.id.tv_pwd_five || id == R.id.tv_pwd_six) {
            CommonUtil.showKeyboard(mFragment.getActivity(), et_password, true);
        } else if (id == R.id.iv_close) {
            mValidatePayPasswordPopWindow.dismiss();
        } else if (id == R.id.tv_forget_password) {
            mValidatePayPasswordPopWindow.dismiss();
        }
    }
}
